import pylab as plt
import random
import numpy as np
from params import *
import math
import os


datasets = ['bkite','fsquare','livejournal', 'twitter']
lbls = ['Brightkite', 'Foursquare', 'LiveJournal', 'Twitter']
#node_dist = [5651.0,8494.0,5663.0]
#link_dist = [2041.0,1442.0,1792.0]
#degs = [7.88,22.07,9.48,7.0]

NUMPOINTS = 50
data = {}
for dataset in datasets:
    trace_file = os.path.join(WORKDIR, 'gsn', 'traces',dataset, '%s_graph.txt'%dataset)
    print 'Dataset %s'%dataset

    d = []
    s = 0.0
    k = 0
    i = 0
    for line in open(trace_file):
        i += 1
        if i % 1000000 == 0:
            print 'line ', i
        if line.startswith('#'):
            continue
        if random.random() > 0.001:
          continue
        u1,u2,dist = line.split(' ')
        dist = float(dist)
        d.append(dist)
        s += dist
        k += 1

    avg_dist = s/k
    print "average ", avg_dist
    print "links ", k
    print min(d)
    d = map(lambda x: max(1.01,x), d)
    print min(d)
    N = len(d)
    #harmonic = math.exp(sum(map(lambda x: math.log(x),d))/N)
    #print 'Harmonic mean ', harmonic
    l = len(filter(lambda x: x < 1000, d))
    print 'fraction less than 1000: ', 1.0*l/k

    l1 = 0
    l2 = math.log10(max(d)) 
    l2 = math.ceil(l2)

    bins = 10**np.linspace(l1,l2, NUMPOINTS)
    cdf1,bins1,xx = plt.hist(d,bins=bins,cumulative=True,normed=False)
    plt.close()
    bins1 = bins1[:-1]
    bins1_norm = map(lambda i: 1.0*i/avg_dist,bins1)
    tot = cdf1[-1]
    cdf1 = [1.0*i/tot for i in cdf1]
    
    data.setdefault(dataset,{})['links'] = (bins1,cdf1)


plt.figure()
plt.clf()
plt.axes(FIG_AXES2)
m = 'x'
legs = []
for dataset,m in zip(sorted(data),markers):
    print dataset,m
    x_l,c_l = data[dataset]['links']
    #x_n,c_n = data[dataset]['nodes']
    p1, = plt.semilogx(x_l,c_l,'k%s'%m, mfc='None')
    #f_line, = plt.semilogx(x_l,c_l,'k-')
    #plt.semilogx(x_n,c_n,'k%s'%m, mfc='None')
    #n_line, = plt.semilogx(x_n,c_n,'k:')
    legs.append(p1)
l1 = plt.legend(legs,lbls,loc='upper left',numpoints=1, ncol=1)
#l2 = plt.legend([f_line,n_line],['Friends','Users'],
#        loc='lower right')
#l2 = plt.legend([f_line],['Friends'],
#        loc='lower right')
plt.gca().add_artist(l1)
plt.xlabel('Distance [km]')
plt.ylabel('CDF')
plt.grid(True)
plt.axis([0,20000,0,1])
plt.savefig('four_spatial_distances.pdf')
plt.close()
